<template>
  <div>
    <el-select v-model="query" placeholder="请选择所在城市">
      <el-option
        v-for="item in cityData"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      >
      </el-option>
    </el-select>
    <el-button type="primary" @click="queryCity">查询城市房源</el-button>
    <el-button type="primary" style="margin-left: 10px" @click="addHousing"
      >添加房源</el-button
    >
    <el-dialog
      title="添加房源"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        ref="housingResourceForm"
        :model="housingResourceForm"
        :rules="rules"
        label-width="150px"
      >
        <el-form-item label="小区名称" prop="communityName">
          <el-input v-model.trim="housingResourceForm.communityName"></el-input>
        </el-form-item>
        <el-form-item label="房屋详细地址" prop="houseAddress">
          <el-input v-model.trim="housingResourceForm.houseAddress"></el-input>
        </el-form-item>
        <el-form-item label="房屋面积" prop="houseArea">
          <el-input v-model.number="housingResourceForm.houseArea"></el-input>
        </el-form-item>
        <el-form-item label="所在城市" prop="houseCity">
          <el-select
            v-model.number="housingResourceForm.houseCity"
            placeholder="请选择所在城市"
          >
            <el-option
              v-for="item in allCity"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房屋简介" prop="houseDesc">
          <el-input v-model.trim="housingResourceForm.houseDesc"></el-input>
        </el-form-item>
        <el-form-item label="房屋总楼层" prop="houseFloor">
          <el-input v-model.number="housingResourceForm.houseFloor"></el-input>
        </el-form-item>
        <el-form-item prop="houseImage">
          <el-upload
            class="upload-demo"
            action="http://100.100.148.3:8080/house/upload"
            :on-remove="singleHandleRemove"
            :on-success="singleUpPass"
            :multiple="false"
            accept="jpg,jpeg,png,gif,bmp,tiff,ai,cdr,eps"
            :on-change="onchange"
            :auto-upload="true"
            :limit="1"
            list-type="picture"
          >
            <el-button size="small" type="primary"
              >点击上传房屋简介照片</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件,且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="房屋规格(几室几厅)" prop="houseModel">
          <el-input v-model.trim="housingResourceForm.houseModel"></el-input>
        </el-form-item>
        <el-form-item label="房屋朝向" prop="houseOriented">
          <el-select
            v-model.trim="housingResourceForm.houseOriented"
            placeholder="请选择房屋朝向"
          >
            <el-option label="东" value="东"></el-option>
            <el-option label="南" value="南"></el-option>
            <el-option label="西" value="西"></el-option>
            <el-option label="北" value="北"></el-option>
            <el-option label="东北" value="东北"></el-option>
            <el-option label="东南" value="东南"></el-option>
            <el-option label="西南" value="西南"></el-option>
            <el-option label="西北" value="西北"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="装修风格" prop="houseStyle">
          <el-input v-model.trim="housingResourceForm.houseStyle"></el-input>
        </el-form-item>
        <el-form-item label="房屋标题" prop="houseTitle">
          <el-input v-model.trim="housingResourceForm.houseTitle"></el-input>
        </el-form-item>
        <el-form-item label="出租方式" prop="houseType">
          <el-select
            v-model.trim="housingResourceForm.houseType"
            placeholder="请选择出租方式"
          >
            <el-option label="合租" value="合租"></el-option>
            <el-option label="整租" value="整租"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="imgs">
          <el-upload
            class="upload-demo"
            action="http://100.100.148.39:8080/house/multipleUpload"
            :on-remove="handleRemove"
            list-type="picture"
            :on-success="multiUpPass"
            :multiple="true"
            :auto-upload="true"
            :on-change="onchange"
            accept="jpg,jpeg,png,gif,bmp,tiff,ai,cdr,eps"
            :limit="3"
            name="files"
          >
            <el-button size="small" type="primary"
              >点击上传房屋简介照片</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件,且不超过500kb
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="价格/每日" prop="price">
          <el-input v-model.number="housingResourceForm.price"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('housingResourceForm')"
            >立即添加</el-button
          >
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div>
      <el-table
        :data="showHousingResource"
        height="580"
        border
        style="width: 80vw"
        :row-style="{ height: '52.5px' }"
      >
        <el-table-column
          prop="publishTime"
          label="创建日期"
          width="250"
          fixed
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="houseTitle"
          label="房屋标题"
          width="400"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="houseModel"
          label="房屋规格"
          align="center"
          width="200"
        >
        </el-table-column>
        <el-table-column
          prop="houseFloor"
          label="房屋总楼层"
          align="center"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="houseOriented"
          label="房屋朝向"
          width="120"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="houseStyle"
          label="装修风格"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="houseType"
          label="出租方式"
          align="center"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="houseAddress"
          label="房屋详细地址"
          width="400"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="price" label="价格" align="center" width="120">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small"
              >查看房间</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <pagination :total="companiesCount" @transfer="CurrentChange">
        </pagination>
      </div>
    </div>
    <el-dialog
      title="房间号"
      :visible.sync="dialogVisibles"
      width="30%"
      :before-close="handleCloses"
    >
      <el-input
        style="width: 21vw"
        placeholder="请输入要添加的房间号..."
        v-model.number="addRoomNumInput"
        clearable
      ></el-input>
      <el-button type="primary" @click="getAddRoom" style="margin-left: 10px"
        >添加房间号</el-button
      >
      <el-table :data="roomNum" height="300" style="width: 80vw" border>
        <el-table-column
          prop="number"
          label="房间号"
          fixed
          align="center"
          width="206"
        >
        </el-table-column>
        <el-table-column
          prop="id"
          label="删除"
          fixed
          align="center"
          width="206"
        >
          <template #default="{ row }">
            <div>
              <a href="#" @click.prevent="getDeleteRoom(row.id)">删除</a>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <pagination :total="companiesCount" @transfer="CurrentChange">
        </pagination>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getQueryHousingResourceAPI,
  getHousingResourceAPI,
  getFindHouseAPI
} from '@/api/getHousingResourceAPI'
import { getRoomAPI, getAddRoomAPI } from '@/api/getRoomAPI'
import request from '@/untils/request'
import { getFindCityAPI } from '@/api/Home/getHomeAPI'
import pagination from '@/components/pagination/MyPagination.vue'
export default {
  data() {
    return {
      // 每页的数据数量
      companiesCount: 10,
      cityData: [],
      houseId: '',
      addRoomNumInput: '',
      close: true,
      query: '',
      dialogVisibles: false,
      dialogVisible: false,
      housingResourceForm: {
        // 小区名称
        communityName: '',
        // 房屋详细地址
        houseAddress: '',
        // 房屋面积
        houseArea: '',
        // 所在城市id
        houseCity: '',
        // 房屋简介
        houseDesc: '',
        // 房屋总楼层
        houseFloor: '',
        // 房屋简介照片
        houseImage: '',
        // 房屋规格（几室几厅）
        houseModel: '',
        // 房屋朝向
        houseOriented: '',
        // 装修风格
        houseStyle: '',
        // 房屋标题
        houseTitle: '',
        // 出租方式
        houseType: '',
        // 房屋详情照片
        imgs: [],
        // 价格
        price: '',
        // 房东
        publisherId: localStorage.getItem('id'),
        // 房东联系方式
        publisherPhone: localStorage.getItem('phone')
      },
      params: {
        page: 1,
        size: 10,
        houseId: '',
        publisherId: 44
      },
      showHousingResource: [],
      roomNum: [],
      // 分页标识
      identification: '',
      allCity: '',
      houseCityFind: [],
      rules: {
        communityName: [
          { required: true, message: '请输入小区名称', trigger: 'blur' }
        ],
        houseAddress: [
          { required: true, message: '请输入房屋详细地址', trigger: 'blur' }
        ],
        houseArea: [
          {
            type: 'number',
            required: true,
            message: '请输入房屋面积',
            trigger: 'blur'
          }
        ],
        houseCity: [
          {
            type: 'number',
            required: true,
            message: '请选择所在城市',
            trigger: 'change'
          }
        ],
        houseDesc: [
          {
            type: 'string',
            required: true,
            message: '请输入房屋简介',
            trigger: 'blur'
          }
        ],
        houseFloor: [
          {
            type: 'number',
            required: true,
            message: '请输入房屋总楼层',
            trigger: 'blur'
          }
        ],
        houseImage: [
          { required: true, message: '请上传简介照片文件', trigger: 'change' }
        ],
        houseModel: [
          {
            type: 'string',
            required: true,
            message: '请输入房屋规格(几室几厅)',
            trigger: 'blur'
          }
        ],
        houseOriented: [
          { required: true, message: '请选择房屋朝向', trigger: 'change' }
        ],
        houseTitle: [
          { required: true, message: '请输入房屋标题', trigger: 'blur' }
        ],
        houseType: [
          {
            type: 'string',
            required: true,
            message: '请选择出租方式',
            trigger: 'change'
          }
        ],
        imgs: [
          { required: true, message: '请上传房屋详情照片', trigger: 'change' }
        ],
        price: [
          {
            type: 'number',
            required: true,
            message: '请输入价格',
            trigger: 'blur'
          }
        ],
        houseStyle: [
          {
            type: 'string',
            required: true,
            message: '请选择装修风格',
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    // 分页跳转
    CurrentChange(currentPage) {
      // 把当前页码给当前页面
      this.params.page = currentPage

      if (this.identification === 1) {
        this.getHousingResource()
      } else if (this.identification === 2) {
        this.queryCity()
      } else if (this.identification === 3) {
        this.getRoom()
      }
    },
    // 关闭对话框
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.$refs.housingResourceForm.resetFields()
          done()
        })
        .catch((_) => {})
    },
    // 关闭对话框
    handleCloses(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.addRoomNumInput = ''
          done()
        })
        .catch((_) => {})
    },
    // 房源表单取消按钮
    cancel() {
      this.dialogVisible = false
      this.$refs.housingResourceForm.resetFields()
    },
    // 查询城市房源
    async queryCity() {
      const { data: res } = await getFindHouseAPI({
        page: this.params.page,
        size: this.params.size,
        houseCity: this.query,
        publisherId: localStorage.getItem('id')
      })
      this.showHousingResource = res.data.houses
      this.companiesCount = res.data.totalElements
      this.identification = 2
    },
    // 查看房间
    handleClick(row) {
      this.houseId = row.id
      this.params.houseId = row.id
      this.dialogVisibles = true
      this.getRoom()
    },
    // 添加房间号
    async getAddRoom() {
      if (this.addRoomNumInput === null) return
      const { data: res } = await getAddRoomAPI({
        number: this.addRoomNumInput,
        houseId: this.houseId
      })
      if (res.code === 20011) {
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success'
        })
        this.addRoomNumInput = ''
      } else {
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'warning'
        })
      }
      this.getRoom()
    },
    // 打开添加房源表单
    async addHousing() {
      this.dialogVisible = true
      const { data: res } = await getFindCityAPI({ delflag: 0 })
      this.allCity = res.data.allCity
    },
    // 删除房间号
    async getDeleteRoom(id) {
      const confirmResult = await this.$confirm(
        '此操作将删除房间号,是否继续?',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消了删除')
      const { data: res } = await request.post(`/room/delete/${id}`)
      if (res.code !== 20021) return this.$message.error('删除失败!')
      this.$message.success('删除成功')
      this.getRoom()
    },
    // 查询房间号
    async getRoom() {
      const { data: res } = await getRoomAPI(this.params)
      this.roomNum = res.data.rooms
      this.identification = 3
      this.companiesCount = res.data.totalElements
    },
    // 提交添加房源表单
    async onSubmit(housingResourceForm) {
      this.$refs[housingResourceForm].validate(async(valid) => {
        if (!valid) return
        const { data: res } = await getHousingResourceAPI(
          this.housingResourceForm
        )
        if (res.code === 20011) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success'
          })
          this.$refs[housingResourceForm].resetFields()
          this.dialogVisible = false
          this.getHousingResource()
        } else {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          })
        }
      })
    },
    // 单个文件列表移除文件时的钩子
    singleHandleRemove(file, fileList) {
      if (file.response.data === this.housingResourceForm.houseImage) {
        this.housingResourceForm.houseImage = ''
      }
    },
    // 多个文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      for (let i = 0; i < this.housingResourceForm.imgs.length; i++) {
        if (file.response.data[0] === this.housingResourceForm.imgs[i]) {
          this.housingResourceForm.imgs.splice(i, 1)
        }
      }
    },
    // 渲染页面房源
    async getHousingResource() {
      this.params.publisherId = localStorage.getItem('id')
      Number(this.params.publisherId)
      const { data: res } = await getQueryHousingResourceAPI({
        page: this.params.page,
        size: this.params.size,
        publisherId: this.params.publisherId
      })
      this.showHousingResource = res.data.houses
      this.companiesCount = res.data.totalElements
      this.identification = 1
    },
    // 单个文件上传成功的回调
    singleUpPass(response) {
      if (response.code === 20011) {
        this.housingResourceForm.houseImage = response.data
      }
    },
    // 多个文件上传成功的回调
    multiUpPass(response) {
      if (response.code === 20011) {
        for (let i = 0; i < response.data.length; i++) {
          this.housingResourceForm.imgs.push(response.data[i])
        }
      }
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    onchange(file, fileList) {
      let fileName = file.name
      let uid = file.uid
      let pos = fileName.lastIndexOf('.')
      let lastName = fileName.substring(pos, fileName.length)
      if (
        lastName.toLowerCase() !== '.jpg' &&
        lastName.toLowerCase() !== '.jpeg' &&
        lastName.toLowerCase() !== '.png' &&
        lastName.toLowerCase() !== '.gif' &&
        lastName.toLowerCase() !== '.bmp' &&
        lastName.toLowerCase() !== '.tiff' &&
        lastName.toLowerCase() !== '.ai' &&
        lastName.toLowerCase() !== '.cdr' &&
        lastName.toLowerCase() !== '.eps'
      ) {
        this.$message.error(
          '文件必须为.jpg,.jpeg,.png,.gif,.bmp,.tiff,.ai,.cdr,.eps 类型'
        )
        // this.resetCompressData()
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
        return
      }
      // 限制上传文件的大小
      const isLt = file.size / 1024 / 5 >= 1 && file.size / 1024 / 1024 / 2 <= 1
      if (!isLt) {
        this.$message.error('上传文件大小不得小于5KB,不得大于2MB!')
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
      }
      return isLt
    },
    async queryCityHousing() {
      const { data: res } = await getFindCityAPI({ delflag: 0 })
      this.cityData = res.data.allCity
    }
  },
  created() {
    this.getHousingResource()
    this.queryCityHousing()
  },
  components: {
    pagination
  }
}
</script>
<style lang="less" scoped>
.pagination {
  text-align: center;
}
</style>
